package com.eportal.service.impl;

import com.eportal.aop.LogAnnotation;
import com.eportal.base.BaseDAO;
import com.eportal.dao.TCbuildingEntityMapper;
import com.eportal.domain.CBuilding;
import com.eportal.domain.CInstallUnit;
import com.eportal.domain.CRoom;
import com.eportal.domain.Sysopt;
import com.eportal.service.CBuildingService;
import com.eportal.service.CInstallUnitService;
import com.eportal.service.CRoomService;
import com.eportal.vo.controller.background.cbuilding.CBuildingSelectListVO;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 楼栋管理业务逻辑接口实现
 */
@Service("cBuildingService")
public class CBuildingServiceImpl implements CBuildingService {

	private Map<String, Object> result = new HashMap<String, Object>();
	private static Logger log = Logger.getLogger(CBuildingServiceImpl.class.getName());

	@Resource
    private CInstallUnitService cInstallUnitService;
	@Resource
	private CRoomService cRoomService;
	@Resource(name="dao")
	private BaseDAO dao;

	@Resource
	private TCbuildingEntityMapper tCbuildingDao;

	@Override
    public List<CBuilding> list(String where) {
    	List<CBuilding> list= null;
    	if (where == null) {
    		list = dao.query(" from CBuilding");
		}else{
			list = dao.query(" from CBuilding "+where);
		}
    	return list;
    }
	public List<Map<String, Object>> listReturnMap(String sql) {
		List<Map<String, Object>> list = dao.queryBySql(sql);
		return list;
	}

    @Override
    public CBuilding add(CBuilding cBuilding) throws Exception {
    	dao.save(cBuilding);
        return cBuilding;
    }

    @Override
    public void delete(Long id) {
    	CBuilding cBuilding = (CBuilding) dao.getById(CBuilding.class, id);
    	dao.delete(cBuilding);
    }

    @Override
    public void delete(List<Long> ids) {
        for (Long id : ids) {
            delete(id);
        }
    }

    public CBuilding get(Long sid) {
        return (CBuilding) dao.getById(CBuilding.class, sid);
    }

    @Override
    public void update(CBuilding cBuilding) throws Exception {

        dao.update(cBuilding);
    }


	/**
     * 楼栋新增保存方法
     * @throws IOException
     */
	@Override
    @LogAnnotation(operateDescribe="楼栋新增")
    public Map<String, Object> addMethod(int building1, int building2, String preBuilding, int unit, String preUnit, int floor, int room, String communityId){
		try {
            	Sysopt  user= (Sysopt)getSession().getAttribute("user");
            	CBuilding cBuilding;
            	CInstallUnit cInstallUnit;
            	CRoom cRoom;
            	StringBuffer sqlCbuding = new StringBuffer("select t.cbname,t.sid from T031_CBUILDING t where t.communityid='");
            	sqlCbuding.append(communityId);
            	sqlCbuding.append("'");
            	List<Map<String, Object>> buidingNameMap = listReturnMap(sqlCbuding.toString());

            	for (; building1 <= building2; building1++) {
            		String ifNewBuding= NeedNewBuding(buidingNameMap,preBuilding,building1,"栋");
            		String cBuildingId = null;
            		if("true".equals(ifNewBuding)){
            			cBuilding = new CBuilding();
            			StringBuilder sb = new StringBuilder();
            			sb.append(preBuilding).append(building1).append("栋");
            			cBuilding.setCbName(sb.toString());
            			cBuilding.setCommunityId(communityId);
            			cBuilding.setcUserName(Long.toString(user.getSid()));
            			cBuilding.setcTime(new Timestamp(System.currentTimeMillis()));
            			cBuilding = add(cBuilding);
            			cBuildingId = cBuilding.getSid().toString();
            			System.out.println("cBuilding新建："+building1);
            		}else{
            			cBuildingId = ifNewBuding;
            			System.out.println("cBuilding没有新建："+building1);
            		}

            		StringBuffer sqlUnit = new StringBuffer("select * from T032_CINSTALLUNIT t where t.cbuildingid='");
            		sqlUnit.append(cBuildingId);
            		sqlUnit.append("'");
                	List<Map<String, Object>> unitNameMap = listReturnMap(sqlUnit.toString());
        			for(int unitNum=1;unitNum<=unit;unitNum++){
        				String ifNewUnit= NeedNewBuding(unitNameMap,preUnit,unitNum,"单元");
                		String unitId = null;
                		if("true".equals(ifNewUnit)){
                			cInstallUnit = new CInstallUnit();
                			StringBuilder sbu = new StringBuilder();
                			sbu.append(preUnit).append(unitNum).append("单元");
                			cInstallUnit.setCbName(sbu.toString());
                			cInstallUnit.setcBuildingId(cBuildingId);
                			cInstallUnit.setcUserName(Long.toString(user.getSid()));
                			cInstallUnit.setcTime(new Timestamp(System.currentTimeMillis()));
                			cInstallUnit = cInstallUnitService.add(cInstallUnit);
                			unitId = cInstallUnit.getSid().toString();
                			System.out.println("unit新建，unitId："+unitNum);
                		}else{
                			unitId = ifNewUnit;
                			System.out.println("unit没有新建，unitId："+unitNum);
                		}

                		StringBuffer sqlRoom = new StringBuffer("select t.sid,t.room_no as roomno,t.floor_no as floorno from T035_ROOM t where t.unit_id ='");
                		sqlRoom.append(unitId);
                		sqlRoom.append("'");
                    	List<Map<String, Object>> roomNameMap = listReturnMap(sqlRoom.toString());

                    	for(int floorNum=1;floorNum<=floor;floorNum++){
        					for(int roomNum=1;roomNum<=room;roomNum++){
        						if(NeedNewRoom(roomNameMap,floorNum,roomNum)){
        							cRoom = new CRoom();
        							cRoom.setCommunityId(communityId);
        							cRoom.setUnitId(unitId);
        							cRoom.setFloorNo(floorNum);
        							cRoom.setRoomNo(floorNum+String.format("%02d",roomNum));
        							cRoom.setcUserName(Long.toString(user.getSid()));
        							cRoom.setcTime(new Timestamp(System.currentTimeMillis()));
        							cRoomService.add(cRoom);
        							System.out.println("Room新建，RoomId："+floorNum+String.format("%02d",roomNum));
        						}else{
        							System.out.println("Room没有新建："+floorNum+String.format("%02d",roomNum));
        							continue;
        						}
        					}
        				}
        			}
				}
                result.put("code", 1);
                result.put("msg", "操作成功");
                result.put("objectId", "");
		} catch (Exception e) {
			log.error("楼栋管理保存失败", e);
			result.put("code", 0);
			result.put("msg", "操作失败");
		}
        return result;
    }

	private boolean NeedNewRoom(List<Map<String, Object>> roomNameMap, int floorNum, int roomNum) {
		if (roomNameMap == null) {//未创建
			return true;
		}else{
			for (Map<String, Object> map : roomNameMap) {
				String bname = floorNum+String.format("%02d",roomNum);
				if(bname.equals(map.get("ROOMNO").toString())){
					return false;
				}else{
					continue;
				}
			}
			return true;
		}
	}
	private String NeedNewBuding(List<Map<String, Object>> buidingNameMap, String preBuilding, int building1,String endName) {
		if (buidingNameMap == null) {//未创建
			return "true";
		}else{
			for (Map<String, Object> map : buidingNameMap) {
				String bname = preBuilding+building1+endName;
				if(bname.equals(map.get("CBNAME").toString())){
					return map.get("SID").toString();
				}else{
					continue;
				}
			}
			return "true";
		}
	}
	public HttpSession getSession() {
        return ServletActionContext.getRequest().getSession();
    }



//todo ----------------------------------------------------------------------------------------------------------------------


	/**
	 * 楼栋下拉列表
	 *
	 * @param communityId 小区id
	 * @param user        当前用户
	 * @param userRole    当前用户userRole
	 * @return
	 * @author Saber
	 * @Date 2017/8/10 上午9:07
	 */
	@Override
	public List<CBuildingSelectListVO> selectList(String communityId, Sysopt user, int userRole) {
		if (StringUtils.isBlank(communityId)) {
			communityId = user.getCommunityId();
		}
		return tCbuildingDao.selectList(communityId,user,userRole);
	}
}
